/*
 * MDNSView.java
 */
package mdnsapp;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import javax.jmdns.ServiceInfo;
import javax.jmdns.impl.JmDNSImpl;
import javax.swing.DefaultListModel;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * The application's main frame.
 */
public class MDNSView extends FrameView {

    static class OverlayData // subclass for storing overlay information..like supernodes..clients , services..
    {

        String Name;
        Vector supernode;
        Vector client;
        Hashtable service;

        public OverlayData() {
            this.supernode = new Vector();
            this.client = new Vector();
            this.service = new Hashtable(); // taken as hash because I need service name and its type when resolving for details....
        }

        public OverlayData(String name) {
            this.Name = name;
            this.supernode = new Vector();
            this.client = new Vector();
            this.service = new Hashtable();
        }
    }

    public MDNSView(SingleFrameApplication app) {

        super(app);

        initComponents();


        // ServiceTypePane.setViewportView(servicesPanel);

        //ServiceList.setVisible(false);
        ////////////// <Qaisar>...
        this.ConfigFile = "../config/dht.cfg";
        overlayList.setModel(overlayListModel);
        ClientsList.setModel(ClientsListModel);
        SupernodeList.setModel(SupernodeListModel);
        OverLayServiceList.setModel(OverLayServiceListModel);

        //////////////// </Qaisar>..

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    /*<Qaisar>
    startDNS();
    booting(this.superNodeServiceType);
    registerServiceListerners();
    //</Qaisar>
     */
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = MDNSApp.getApplication().getMainFrame();
            aboutBox = new MDNSAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        MDNSApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        Info = new javax.swing.JTextArea();
        RegisterButton = new javax.swing.JButton();
        DiscoverOverlayButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        overlayList = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        SupernodePanel = new javax.swing.JPanel();
        ServiceTypePane = new javax.swing.JScrollPane();
        SupernodeList = new javax.swing.JList();
        OverlayServicespanel = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        OverLayServiceList = new javax.swing.JList();
        ClientsPanel = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        ClientsList = new javax.swing.JList();
        ConnectOverlayButton = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setPreferredSize(new java.awt.Dimension(300, 200));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(mdnsapp.MDNSApp.class).getContext().getResourceMap(MDNSView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        Info.setColumns(20);
        Info.setRows(5);
        Info.setName("Info"); // NOI18N
        jScrollPane1.setViewportView(Info);

        RegisterButton.setText(resourceMap.getString("RegisterButton.text")); // NOI18N
        RegisterButton.setName("RegisterButton"); // NOI18N
        RegisterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RegisterButtonActionPerformed(evt);
            }
        });

        DiscoverOverlayButton.setText(resourceMap.getString("DiscoverOverlayButton.text")); // NOI18N
        DiscoverOverlayButton.setName("DiscoverOverlayButton"); // NOI18N
        DiscoverOverlayButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DiscoverOverlayButtonActionPerformed(evt);
            }
        });

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        overlayList.setName("overlayList"); // NOI18N
        overlayList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                overlayListMouseClicked(evt);
            }
        });
        overlayList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                overlayListValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(overlayList);

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        SupernodePanel.setName("SupernodePanel"); // NOI18N

        ServiceTypePane.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        ServiceTypePane.setName("ServiceTypePane"); // NOI18N

        SupernodeList.setName("SupernodeList"); // NOI18N
        SupernodeList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                SupernodeListMouseClicked(evt);
            }
        });
        SupernodeList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                SupernodeListValueChanged(evt);
            }
        });
        ServiceTypePane.setViewportView(SupernodeList);

        javax.swing.GroupLayout SupernodePanelLayout = new javax.swing.GroupLayout(SupernodePanel);
        SupernodePanel.setLayout(SupernodePanelLayout);
        SupernodePanelLayout.setHorizontalGroup(
            SupernodePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ServiceTypePane, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
        );
        SupernodePanelLayout.setVerticalGroup(
            SupernodePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ServiceTypePane, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab(resourceMap.getString("SupernodePanel.TabConstraints.tabTitle"), SupernodePanel); // NOI18N

        OverlayServicespanel.setName("OverlayServicespanel"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        OverLayServiceList.setName("OverLayServiceList"); // NOI18N
        OverLayServiceList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                OverLayServiceListValueChanged(evt);
            }
        });
        jScrollPane3.setViewportView(OverLayServiceList);

        javax.swing.GroupLayout OverlayServicespanelLayout = new javax.swing.GroupLayout(OverlayServicespanel);
        OverlayServicespanel.setLayout(OverlayServicespanelLayout);
        OverlayServicespanelLayout.setHorizontalGroup(
            OverlayServicespanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
        );
        OverlayServicespanelLayout.setVerticalGroup(
            OverlayServicespanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab(resourceMap.getString("OverlayServicespanel.TabConstraints.tabTitle"), OverlayServicespanel); // NOI18N

        ClientsPanel.setName("ClientsPanel"); // NOI18N

        jScrollPane4.setName("jScrollPane4"); // NOI18N

        ClientsList.setName("ClientsList"); // NOI18N
        ClientsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                ClientsListValueChanged(evt);
            }
        });
        jScrollPane4.setViewportView(ClientsList);

        javax.swing.GroupLayout ClientsPanelLayout = new javax.swing.GroupLayout(ClientsPanel);
        ClientsPanel.setLayout(ClientsPanelLayout);
        ClientsPanelLayout.setHorizontalGroup(
            ClientsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
        );
        ClientsPanelLayout.setVerticalGroup(
            ClientsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab(resourceMap.getString("ClientsPanel.TabConstraints.tabTitle"), ClientsPanel); // NOI18N

        ConnectOverlayButton.setText(resourceMap.getString("ConnectOverlayButton.text")); // NOI18N
        ConnectOverlayButton.setName("ConnectOverlayButton"); // NOI18N
        ConnectOverlayButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConnectOverlayButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(DiscoverOverlayButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(RegisterButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 632, Short.MAX_VALUE)
                    .addComponent(ConnectOverlayButton))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(9, 9, 9)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE))
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(DiscoverOverlayButton)
                    .addComponent(RegisterButton)
                    .addComponent(ConnectOverlayButton))
                .addGap(17, 17, 17))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(mdnsapp.MDNSApp.class).getContext().getActionMap(MDNSView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 1037, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 867, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void SupernodeListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SupernodeListMouseClicked
        // TODO add your handling code here:
/*
        ServiceInfo currentService = (ServiceInfo) ServiceInfoList.get(ServiceList.getSelectedIndex());
        System.err.println("Mouse clicked.. size " + ServiceInfoList.size() + " index  " + ServiceList.getSelectedIndex());
        System.err.println("Mouse clicked.." + currentService.getName());

         */
}//GEN-LAST:event_SupernodeListMouseClicked

    private void SupernodeListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_SupernodeListValueChanged
        // TODO add your handling code here:

        if (!evt.getValueIsAdjusting()) {
            if (evt.getSource() == SupernodeList) {
                String name = (String) SupernodeList.getSelectedValue();
                if (name == null) {
                    Info.setText("");
                } else {
                    String type;
                    if (connected) {
                        type = MDNSModule.superNodeServiceType;
                    } else {
                        type = MDNSModule.bootstrapNodeServiceType;
                    }
                    System.err.println("serviceListValueChanged: Serservicename = " + name + " type = " + type);
                    ServiceInfo service = dns.getServiceInfo(type, ConnectedOverlay + ":" + name);
                    if (service == null) {
                        Info.setText("service not found");
                        System.err.println("service not found, Let me resolve it..");

                    } else {
                        System.err.println("I am in serviceListValueChanged... serviceInfo = " + service);
                        System.err.println("service found");
                        dns.requestServiceInfo(type, ConnectedOverlay + ":" + name);
                    }
                }
            }
        }
}//GEN-LAST:event_SupernodeListValueChanged

    private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegisterButtonActionPerformed
        // TODO add your handling code here:
        RegistrationManager RegMan = new RegistrationManager();
        RegMan.setVisible(true);

    }//GEN-LAST:event_RegisterButtonActionPerformed

    private void DiscoverOverlayButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DiscoverOverlayButtonActionPerformed
        // TODO add your handling code here:

        int totalBytes = (dns.getCache() + "").getBytes().length;
        System.err.println("Cache button clicked.. " + totalBytes);
    /*
    for (Iterator i = supernodes.iterator(); i.hasNext();) {
    String name = (String) i.next();
    ServiceInfo service = dns.getServiceInfo(superNodeServiceType, name);
    if (service == null) {
    Info.setText("service not found");
    } else {
    System.err.println("I am in cacheButtonActionperformed... serviceInfo = " + service);
    System.err.println("service found");
    dns.requestServiceInfo(superNodeServiceType, name);
    }

    }
     */

}//GEN-LAST:event_DiscoverOverlayButtonActionPerformed

    private void overlayListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_overlayListValueChanged
        // TODO add your handling code here:
    }//GEN-LAST:event_overlayListValueChanged

    private void overlayListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_overlayListMouseClicked
        // TODO add your handling code here:

        if (evt.getSource() == overlayList) {
            String overlay = (String) overlayList.getSelectedValue();
            ConnectedOverlay = overlay;
            SupernodeListModel.clear(); // clearing all supernodes of previously selected overlay..
            OverLayServiceListModel.clear(); // clearing all services of previously selected overlay..
            ClientsListModel.clear(); // clearing all clients of previously selected overlay..
            System.err.println("Overlay selected: " + overlay);
            if (overlay == null) {
                Info.setText("");
            } else {
                System.err.println("overlayListMouseClicked:Check:Overlayname:" + overlay + ":");

                if (!connected) {
                    if (bootStrapNode != null) {
                        SupernodeListModel.addElement(bootStrapNode);
                    }
                } else {
                    refreshData(overlay);
                }


    }//GEN-LAST:event_overlayListMouseClicked
        }
    }

    void refreshData(String overlay) {

        OverlayData data = (OverlayData) systemData.get(overlay);
        SupernodeListModel.clear(); // clearing all supernodes of previously selected overlay..
        OverLayServiceListModel.clear(); // clearing all services of previously selected overlay..
        ClientsListModel.clear(); // clearing all clients of previously selected overlay..
        for (Iterator itr = data.supernode.iterator(); itr.hasNext();) {  //displaying the supernodes of this selected overlay
            System.err.println(" No. of supernodes in " + overlay + " = " + data.supernode.size());
            String element = (String) itr.next();
            if (!SupernodeListModel.contains(element)) {
                System.out.println("Adding " + element + " in supernode list of " + overlay + " overlay..");
                SupernodeListModel.addElement(element);
            }
        }
        for (Iterator itr = data.client.iterator(); itr.hasNext();) {  //displaying the clientnodes of this selected overlay
            System.err.println(" No. of clientnodes in " + overlay + " = " + data.client.size());
            String element = (String) itr.next();
            if (!ClientsListModel.contains(element)) {
                System.out.println("Adding " + element + " in clientnode list of " + overlay + " overlay..");
                ClientsListModel.addElement(element);
            }
        }

        for (Enumeration itr = data.service.keys(); itr.hasMoreElements();) {  //displaying the services of this selected overlay
            System.err.println(" No. of services in " + overlay + " = " + data.service.size());
            String element = (String) itr.nextElement();
            if (!OverLayServiceListModel.contains(element)) {
                System.out.println("Adding " + element + " in service list of " + overlay + " overlay..");
                OverLayServiceListModel.addElement(element);
            }
        }

    }
            private void OverLayServiceListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_OverLayServiceListValueChanged
                // TODO add your handling code here:
                if (!evt.getValueIsAdjusting()) {
                    if (evt.getSource() == OverLayServiceList) {
                        String name = (String) OverLayServiceList.getSelectedValue();
                        if (name == null) {
                            Info.setText("");
                        } else {
                            OverlayData data = (OverlayData) systemData.get(ConnectedOverlay);
                            String type = (String) data.service.get(name);
                            System.err.println("serviceListValueChanged: Serservicename = " + name + " type = " + type);
                            ServiceInfo service = dns.getServiceInfo(type, ConnectedOverlay + ":" + name);
                            if (service == null) {
                                Info.setText("service not found");
                                System.err.println("service not found, Let me resolve it..");

                            } else {
                                System.err.println("I am in serviceListValueChanged... serviceInfo = " + service);
                                System.err.println("service found");
                                dns.requestServiceInfo(type, ConnectedOverlay + ":" + name);
                            }
                        }
                    }
                }
            }//GEN-LAST:event_OverLayServiceListValueChanged

            private void ClientsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_ClientsListValueChanged
                // TODO add your handling code here:
                if (!evt.getValueIsAdjusting()) {
                    if (evt.getSource() == ClientsList) {
                        String name = (String) ClientsList.getSelectedValue();
                        if (name == null) {
                            Info.setText("");
                        } else {
                            String type = MDNSModule.clientNodeServiceType;
                            System.err.println("clientListValueChanged: clientname = " + name + " type = " + type);
                            ServiceInfo service = dns.getServiceInfo(type, ConnectedOverlay + ":" + name);
                            if (service == null) {
                                Info.setText("service not found");
                                System.err.println("service not found, Let me resolve it..");

                            } else {
                                System.err.println("I am in clientListValueChanged... serviceInfo = " + service);
                                System.err.println("service found");
                                dns.requestServiceInfo(type, ConnectedOverlay + ":" + name);
                            }
                        }
                    }
                }

            }//GEN-LAST:event_ClientsListValueChanged

            private void ConnectOverlayButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConnectOverlayButtonActionPerformed
                // TODO add your handling code here:
                if (selectedSupernodeInfo == null) {
                    JOptionPane.showMessageDialog(null, "Please select some supernode in order to connect", "No Supernode Select", busyIconIndex);
                    return;
                }
                String ip = ("" + selectedSupernodeInfo.getAddress()).substring(1);
                String port = "" + selectedSupernodeInfo.getPort();
                System.out.println("Please wait while we are trying to connect you to the overlay :" + this.ConnectedOverlay + " with supernode:" + selectedSupernodeInfo.getServer() + " At:" +
                        ip + ":" + port);
                //ConfigFileEdit tmpFile = new ConfigFileEdit(this.dhtCfgFileName);
                //tmpFile.writeSupernodeIP_cfg(ip, port);

                ConfigEditor confEdit = new ConfigEditor(this.ConfigFile);
                confEdit.updateNode(ip, port);
                confEdit.updateGateway(ip, port);

                DHTThread dhtThread = new DHTThread();
                new Thread(dhtThread).start();

                // call connecting code of Scope here...

                refreshData(ConnectedOverlay);
                connected = true;
                Info.setText("Connected to overlay  '" + ConnectedOverlay + "'");
            }//GEN-LAST:event_ConnectOverlayButtonActionPerformed

    class DHTThread implements Runnable {

        public void run() {
            startDHT();
        }

        void startDHT() {
            String s = null;
            System.out.println("I am in startDHT..");
            try {

                /*
                String[] cmd = new String[4];
                cmd[0] = "cmd.exe";
                cmd[1] = "/C";
                cmd[2] = "start C:/cygwin/Cygwin.bat";
                //cmd[3] = "C:/cygwinbin/bash.exe";
                cmd[3] = "run ../bin/dht_run.sh";

                 */
                String command = "cygstart /bin/bash.exe  ../bin/dht_run.sh";

                Process p = Runtime.getRuntime().exec(command);


                //Process p = Runtime.getRuntime().exec("run /bin/bash.exe ../bin/dht_run.sh");
                
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

                BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

                // read the output from the command
                System.out.println("Here is the standard output of the command:\n");
                while ((s = stdInput.readLine()) != null) {
                    System.out.println(s);
                }

                // read any errors from the attempted command

                System.out.println("Here is the standard error of the command (if any):\n");
                while ((s = stdError.readLine()) != null) {
                    System.out.println(s);
                }

                //System.exit(0);
            } catch (Exception e) {
                System.out.println("exception happened - here's what I know: ");
                e.printStackTrace();
                System.exit(-1);
            }

        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList ClientsList;
    private javax.swing.JPanel ClientsPanel;
    private javax.swing.JButton ConnectOverlayButton;
    private javax.swing.JButton DiscoverOverlayButton;
    javax.swing.JTextArea Info;
    private javax.swing.JList OverLayServiceList;
    private javax.swing.JPanel OverlayServicespanel;
    private javax.swing.JButton RegisterButton;
    private javax.swing.JScrollPane ServiceTypePane;
    private javax.swing.JList SupernodeList;
    private javax.swing.JPanel SupernodePanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JList overlayList;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    DefaultListModel OverLayServiceListModel = new DefaultListModel();
    DefaultListModel overlayListModel = new DefaultListModel();
    Vector ServiceInfoList = new Vector();
    Hashtable ServiceNameTypeHash = new Hashtable();
    String ConnectedOverlay = "";
    Vector supernodes = new Vector();
    SNandServicesPanel servicesPanel;
    DefaultListModel ClientsListModel = new DefaultListModel();
    DefaultListModel SupernodeListModel = new DefaultListModel();
    Hashtable systemData = new Hashtable();
    static JmDNSImpl dns;
    String ConfigFile;
    ServiceInfo selectedSupernodeInfo = null;
    boolean connected = false;
    String bootStrapNode = null;
}
